package com.zhy.learning.demo.fail.fast;

import org.apache.poi.ss.formula.functions.T;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 验证多线程的fail-fast机制
 * 概念：fail-fast 机制是java集合(Collection)中的一种错误机制。当多个线程对同一个集合的内容进行操作时，就可能会产生fail-fast事件。
 */
public class Test {

    private static List<String> list = new ArrayList<>();

    public static void main(String[] args) {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 6; i++) {
                    list.add(String.valueOf("线程一" + i));
                    printAll();
                }
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 6; i++) {
                    list.add(String.valueOf("线程二" + i));
                    printAll();
                }
            }
        });

        t1.start();
        t2.start();
    }

    private static void printAll() {
        String value = null;
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println((String) iterator.next());
        }
    }
}
